package LeetCode;

public class Code208_Trie {

    private Code208_Trie[] children = new Code208_Trie[26];
    private boolean isEnd = false;

    public Code208_Trie() {}

    // Inserts a word into the trie.
    public void insert(String word) {
        char[] chas = word.toCharArray();
        Code208_Trie tmp = this;
        for (int i = 0; i < chas.length; i++) {
            if (tmp.children[chas[i] - 'a'] == null){
                tmp.children[chas[i] - 'a'] = new Code208_Trie();
            }
            tmp = tmp.children[chas[i] - 'a'];
        }
        tmp.isEnd = true;
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        Code208_Trie tmp = this;
        for (char c : word.toCharArray()) {
            if (tmp.children[c - 'a'] == null){
                return false;
            }
            tmp = tmp.children[c - 'a'];
        }
        if (tmp.isEnd){
            return true;
        } else {
            return false;
        }
    }

    // Returns if there is any word in the trie that starts with the given prefix.
    public boolean startsWith(String prefix) {
        Code208_Trie tmp = this;
        for (char c : prefix.toCharArray()) {
            if (tmp.children[c - 'a'] == null){
                return false;
            }
            tmp = tmp.children[c - 'a'];
        }
        return true;
    }

}
